using System.Runtime.InteropServices;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ServoDrivesLib.Model;

[StructLayout(LayoutKind.Explicit, Pack = 1)]
public struct AxisParam
{
    [FieldOffset(0)] public double Unit;
    [FieldOffset(8)] public double Position;
    [FieldOffset(16)] public double Speed;
    [FieldOffset(24)] public double Acceleration;
    [FieldOffset(32)] public double Deceleration;
    [FieldOffset(40)] public double Sramp;
    [FieldOffset(48)] public double FeedbackPosition;
    [FieldOffset(56)] public double FeedbackSpeed;
    [FieldOffset(64)] public double AxisMoveStatus;
    [FieldOffset(72)] public double AxisStatus;
    [FieldOffset(80)] public double AxisError;
    [FieldOffset(88)] public AxisMoveType MoveType;

}

public enum AxisMoveType : long
{
    [System.ComponentModel.Description("绝对运动")]
    Absolute = 1,
    [System.ComponentModel.Description("相对运动")]
    Relative,
    [System.ComponentModel.Description("回零运动")]
    Home,
    [System.ComponentModel.Description("往复运动")]
    Loop,
}
public static class AxisParamEx
{
    public static string GetAxisParamString(this AxisParam axisParam)
    {
        int size = Marshal.SizeOf(typeof(AxisParam));
        double[] ret = new double[size / 8];

        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(axisParam, ptr, false);
        byte[] data = new byte[size];
        Marshal.Copy(ptr, data, 0, size);
        Marshal.FreeHGlobal(ptr);
        Span<byte> buffer = new Span<byte>(data);
        for (int i = 0; i < size; i += 8)
        {
            var tmp = buffer.Slice(i, 8).ToArray();
            ret[i / 8] = BitConverter.ToDouble(tmp, 0);
        }
        return string.Join(",", ret);
    }

    public static AxisParam CreateInit(this AxisParam axisParam)
    {
        axisParam = new AxisParam();
        axisParam.Unit = 10000;
        axisParam.Position = 0;
        axisParam.Speed = 1000;
        axisParam.Acceleration = 0.01;
        axisParam.Deceleration = 0.01;
        axisParam.Sramp = 0.1;

        return axisParam;
    }
}